package ua.kharkov.photo.controllers;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import ua.kharkov.photo.dal.ImageRepository;
import ua.kharkov.photo.dal.UserRepository;
import ua.kharkov.photo.model.Image;
import ua.kharkov.photo.model.UploadItem;
import ua.kharkov.photo.model.User;

@Controller
public class GalleryController extends AbstractController {

	private UserRepository userRepository;
	private ImageRepository imageRepository;

	@Autowired
	public void setUserRepository(UserRepository userRepository) {
		this.userRepository = userRepository;
	}

	@Autowired
	public void setImageRepository(ImageRepository imageRepository) {
		this.imageRepository = imageRepository;
	}

	@RequestMapping(method = RequestMethod.GET, value = "/gallery")
	public String getUploadForm(Model model, HttpServletRequest httpRequest) {
		model.addAttribute(new UploadItem());

		Cookie[] cookies = httpRequest.getCookies();
		if (cookies == null || cookies[0].getValue().equals(""))
			return "redirect:login";

		for (User user : userRepository.getAllUsers()) {
			if (cookies[0].getValue()
					.equals(DigestUtils.shaHex(user.getUserName()
							+ user.getPassword()))) {
				model.addAttribute("loggedUser", user.getUserName());

				List<Image> images = imageRepository.getImagesbyUser(user);
				model.addAttribute("images", images);

				return "gallery";
			}
		}

		return "gallery";
	}

	@RequestMapping(method = RequestMethod.POST, value = "/gallery")
	public String loginUser(Model model, HttpServletRequest httpRequest,
			UploadItem uploadItem) throws IOException {

		Cookie[] cookies = httpRequest.getCookies();

		if (cookies == null || cookies[0].getValue().equals("")) {
			return "redirect:login";
		}

		for (User u : userRepository.getAllUsers()) {
			if (cookies[0].getValue().equals(
					DigestUtils.shaHex(u.getUserName() + u.getPassword()))) {

				Image image = new Image();
				image.setUserId(u.getId());
				image.setData(uploadItem.getFileData().getBytes());

				imageRepository.insertImage(image);

				return "redirect:gallery";

			}
		}

		return "gallery";
	}

}
